package com.apes.framework.plugin.condition.model;

import com.apes.framework.jpa.ApesBean;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.condition.PricingProcedureContext;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能：存取顺序- 包含条件记录存取的层次结构，存取顺序中包含一个或者多个条件表，多个条件表时需指定读取这些表的顺序
 *
 * @author xul
 * @create 2018-11-06 17:11
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = AccessSequences.CONST_TABLE_NAME)
public class AccessSequences implements ApesBean {
    public static final String CONST_TABLE_NAME = "tech_access_sequences";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "存取顺序")
    @Comment("编号")
    private String id;

    @Column(name = "name", nullable = false, length = 120)
    @Comment("描述")
    private String name;

    @OneToMany(mappedBy = "accessSequences", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("step asc")
    private Set<AccessSequencesItem> accessSequencesItems = new HashSet();

    public Set<AccessSequencesItem> getAccessSequencesItems() {
        for (AccessSequencesItem item : accessSequencesItems) {
            item.setAccessSequences(this);
        }
        return accessSequencesItems;
    }

    public boolean process(final PricingProcedureContext context) {
        boolean result = false;
        for (AccessSequencesItem item : accessSequencesItems) {
            Object entity = item.process(context);
            if(entity == null) continue;
            result = context.getConditionTypes().calcValue(context, entity);
            if (result) break;
        }
        return result;
    }
}
